package com.huineta.business.common.security.uutoken;

import java.util.*;
import java.util.concurrent.TimeUnit;
import com.huineta.business.common.tools.core.TokenUtil;
import com.huineta.business.common.security.services.SecurityUser;
import com.huineta.business.common.constant.CacheNameConstant;
import com.huineta.business.common.constant.SecurityConstant;
import com.huineta.business.common.web.exception.auth.token.TokenException;
import com.huineta.business.common.web.exception.auth.token.TokenExpiredException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * Author:       Dmm Lee< bclassline@gmail.com >
 * Date:         2022/11/28
 * Description:  Security User Token 操作服务
 */
@Component
public class SecurityUserTokenService {

    @Resource
    private RedisTemplate<String, SecurityUserToken> redisTemplate;

    /**
     * 创建 Token
     * */
    public SecurityUserToken createToken(SecurityUser securityUser){
        SecurityUserToken userToken = new SecurityUserToken();
        userToken.setToken(TokenUtil.create(securityUser.getId(), securityUser.getUsername()));
        userToken.setSecurityUser(securityUser);
        return userToken;
    }

    /**
     * 存储 Token
     * */
    public String saveToken(SecurityUserToken userToken){
        String key = String.valueOf(UUID.randomUUID());
        redisTemplate.opsForValue().set(CacheNameConstant.TOKEN_NAME_PREFIX + key, userToken,  SecurityConstant.TOKEN_EXPIRATION, TimeUnit.SECONDS);
        return key;
    }

    /**
     * 验证 Token
     * */
    public SecurityUserToken verifyToken(String key, String token) throws TokenException{
        SecurityUserToken securityUserToken = taskToken(key);
        if(securityUserToken == null) throw new TokenExpiredException("token expired");
        TokenUtil.parse(securityUserToken.getToken());
        return securityUserToken;
    }

    /**
     * 获取 Token
     * */
    public SecurityUserToken taskToken(String key){
        return redisTemplate.opsForValue().get(CacheNameConstant.TOKEN_NAME_PREFIX + key);
    }

    /**
     * 销毁 Token
     * */
    public void destroyToken(String key){
        redisTemplate.delete(CacheNameConstant.TOKEN_NAME_PREFIX + key);
    }

}
